<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/4/15 16:24
 * Remark:
 */

namespace App\Service\Auth;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Auth\AuthBasicModel;
use App\Models\Auth\AuthMenuModel;
use App\Models\Auth\AuthRoleModel;
use App\Models\Auth\RoleModel;
use Illuminate\Http\Exceptions\HttpResponseException;

class RoleService
{
    private RoleModel $_roleModel;
    private AuthMenuModel $_authMenuModel;
    private AuthRoleModel $_authRoleModel;
    private AuthBasicModel $_authBasicModel;

    public function __construct()
    {
        $this->_roleModel = new RoleModel();
        $this->_authMenuModel = new AuthMenuModel();
        $this->_authRoleModel = new AuthRoleModel();
        $this->_authBasicModel = new AuthBasicModel();
    }

    /**
     * 创建角色
     * @param $roleData
     * @return mixed
     */
    public function addRole($roleData): mixed
    {
        $currentInfo = TokenFuc::getCurrentStaffInfo();

        $time = time();
        $roleData['company_id'] = $roleData['company_id'] ?? $currentInfo['company_id'];
        $roleData['status'] = BaseConsts::STATUS_NORMAL;
        $roleData['created_at'] = $time;
        $roleData['updated_at'] = $time;
        $res =  $this->_roleModel->addRole($roleData);
        if(!$res){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '新增角色错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        return $res;
    }

    /**
     * 修改角色
     * @param $roleData
     */
    public function editRole($roleData){
        unset($roleData['company_id']);
        unset($roleData['status']);
        $res = $this->_roleModel->editRole($roleData);
        if(!$res){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '修改角色失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    /**
     * 删除角色
     * @param $roleId
     */
    public function deleteRole($roleId)
    {
        $res =  $this->_roleModel->editRole([
            'role_id' => $roleId,
            'status' => BaseConsts::STATUS_DELETE
        ]);
        if(!$res){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '删除角色失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    /**
     * 获取角色详情
     * @param $roleId
     * @return mixed
     */
    public function getRoleInfo($roleId): mixed
    {
        return $this->_roleModel->getRoleInfo($roleId,[
            'role_id',
            'company_id',
            'role_name'
        ]);
    }

    /**
     * 获取角色下拉
     * @return mixed
     */
    public function getRoleSelect(){
        return $this->_roleModel->getRoleSelect();
    }


    /**
     * 获取角色列表
     * @param $pageSize
     * @param $filters
     * @return mixed
     */
    public function getRoleList($pageSize,$filters): mixed
    {
        $query = $this->_roleModel->select([
            'role_id',
            'role_id as key',
            'role_name'
        ])->where('status',BaseConsts::STATUS_NORMAL);
        if($filters){
            $filters = json_decode($filters,true);
            if(isset($filters['role_name']) && $filters['role_name']){
                $query = $query->where('role_name','LIKE',"%".$filters['role_name']."%");
            }
        }
        return $this->_roleModel->getRoleList($query,$pageSize);
    }

    public function getRoleAuthMenu($roleId)
    {
        // 获取权限菜单
        $authMenus = $this->_authMenuModel->getAuthMenuMenu();
        // 获取角色详情
        $roleInfo = $this->_roleModel->getRoleInfo($roleId);
        // 查询当前角色公司下全部权限
        $auths = $this->_authBasicModel->getAuthByCompanyId($roleInfo['company_id'],["auth_id","menu_id"]);
        if($auths){
            $formatAuths = array_column($auths->toArray(),'menu_id',"auth_id");
            // 获取当前角色拥有的权限
            $roleAuths = $this->_authRoleModel->getRoleAuth($roleId);
            // 匹配菜单权限
            $menuRole = [];
            if($roleAuths){
                foreach($roleAuths as $key=>$roleAuth){
                    $menuId = $formatAuths[$roleAuth['auth_id']];
                    $menuRole[$menuId][] = $roleAuth->toArray();
                }
            }

            if($authMenus){
                foreach($authMenus as $key=>$authMenu){
                    $authMenus[$key]['role_auth'] = $menuRole[$authMenu['menu_id']] ?? [];
                }
            }
        }
        return $authMenus;
    }


}